__author__ = 'vladbranzei'

import hashlib
from configs import configs as conf
from pymongo.errors import DuplicateKeyError
from cherrypy import HTTPError
from time import time
import logging

class InboxMapper(object):

    def __init__(self):
        self.foundMessage = None
        self.client = conf.client


    def create(self, vid, game, credentials, message):
        try:
            id = self._get_id(credentials)
            msg = {'msg_id': id, 'content': message}
            logging.info(str(msg))
            result = self.client.hermes.internal.update({"vid": vid, "game": game},{"$push":{"messages": msg}}, upsert=True)

            return result
        except DuplicateKeyError as e:
            raise e
        except Exception as e:
            raise e


    def _get_id(self, credentials):
        id = ''
        now = time()
        m = hashlib.md5()
        m.update(credentials.encode('utf-8'))
        m.update(str(now).encode('utf-8'))

        id = m.hexdigest()
        return id